﻿using System.Net.Sockets;
using System.Net;
using System.Threading;
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace senController.classes
{    
    class NetworkWriter
    {
        private NetworkController _networkController;
        private Queue<commandData> _commands;
        private Stream _stream;

        private bool _switchMode;

        public NetworkWriter(Stream stream, NetworkController networkController, bool mode)
        {
            this._networkController = networkController;
            this._commands = new Queue<commandData>();
            this._stream = stream;
            this._switchMode = mode;
        }

        public Thread Prepare()
        {
            return new Thread(new ThreadStart(Send));
        }

        private void Send()
        {
            try
            {
                BinaryWriter serverstreamw = new BinaryWriter(new BufferedStream(_stream, 1024), Encoding.ASCII);
                while (true)
                {
                    if (_commands.Count > 0)
                    {
                        //stuur een command naar de server.
                        //de buffered stream zorgt er voor dat er onderwater 1 receive wordt gebruikt ipv 3.                     

                        serverstreamw.Write(_commands.Peek().command);
                        //Check if mode has been switched
                        if (!_switchMode)
                            serverstreamw.Write((byte)_commands.Peek().parameters.Length);
                        else
                            serverstreamw.Write(_commands.Peek().parameters.Length);
                        serverstreamw.Write(_commands.Peek().parameters.ToCharArray());

                        serverstreamw.Flush();
                        Console.WriteLine("Command {0} send with parameters: {1}", _commands.Peek().command, _commands.Peek().parameters);

                        //remove the command
                        _commands.Dequeue();
                    }
                    else
                    {
                        Thread.Yield();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }

        public void SetCommand(commandData command)
        {
            _commands.Enqueue(command);
        }

        /// <summary>
        /// Switch network mode between readbyte and readint
        /// </summary>
        /// <param name="value">current switch value</param>
        public void switchMode(bool value)
        {
            this._switchMode = value;
        }
    }    
}